import {
  getMenuList,
  deleteUserMenus
} from '../../api/index'
Page({
  data: {
    loadingShow: true,
    // 根据传入isUser是否true判断当前是否从自己菜谱进入,自己菜谱是可编辑的
    isUser: false,
    menusList: [],
    loadingType: 'loading', //底部加载提示
    deleteDialogShow: false,
    deleteId: '',
  },
  $data: {
    loadingStatus: {
      loading: 'loading',
      end: 'end'
    },
    query: {
      currentPage: 1,
      pageNumber: 10,
      isUser: false,
      searchValue: "",
      classifyName: ""
    }
  },
  getList() {
    const {
      loadingStatus,
      query
    } = this.$data

    const {
      menusList
    } = this.data
    getMenuList(query).then(res => {
      let list = []
      // 根据当前页码判断数组是合并还是赋值
      if (query.currentPage > 1) {
        list = menusList.concat(res.data)
      } else {
        list = res.data
      }

      let loadingType = loadingStatus.loading
      if (res.data.length < this.$data.query.pageNumber) {
        loadingType = loadingStatus.end
      }

      let loadingShow = true
      if (list.length === 0) {
        loadingShow = false
      }

      this.setData({
        loadingShow,
        menusList: list,
        loadingType
      })

      wx.stopPullDownRefresh()
    })
  },

  search(e) {
    this.$data.query.currentPage = 1
    this.$data.query.searchValue = e.detail.value
    this.getList()
  },

  goEdit(e) {
    const {
      id
    } = e.currentTarget.dataset

    wx.navigateTo({
      url: '/pages/EditMenu/index?id=' + id,
    })
  },

  deleteDialogShow(e) {
    const {
      id
    } = e.currentTarget.dataset

    this.setData({
      deleteDialogShow: true,
      deleteId: id
    })


  },

  deleteConfirm() {
    const {
      deleteId: id
    } = this.data
    deleteUserMenus({
      id
    }).then(() => {
      wx.lin.showMessage({
        type: 'success',
        content: '删除成功'
      })
      wx.pageScrollTo({
        scrollTop: 0
      });
      this.$data.query.currentPage = 1
      this.getList()
    })
  },
  onLoad: function () {
    const pages = getCurrentPages()
    const curPage = pages[pages.length - 1] //当前页面
    const options = curPage.options

    if (options.isUser && options.isUser === "true") {
      this.$data.query.isUser = true
      this.setData({
        isUser: true
      })
    }
    if (options.classifyName) {
      this.$data.query.classifyName = options.classifyName
    }
    this.getList()
  },
  onEditSuccess(item) {
    // 实现局部刷新
    const {
      menusList
    } = this.data
    const list = menusList.map(menu => {
      if (menu._id === item._id) {
        return item
      } else {
        return menu
      }
    })

    this.setData({
      menusList: list
    })
  },
  onPullDownRefresh: function () {
    this.$data.query.currentPage = 1
    this.getList()
  },
  onReachBottom: function () {
    if (this.data.loadingType === "loading") {
      this.$data.query.currentPage++
      this.getList()
    }
  },
})